package com.ikonke.iot.alarm.rest;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.ikonke.iot.alarm.domain.R;
import com.ikonke.iot.alarm.email.MailDO;
import com.ikonke.iot.alarm.influxdb.AsyncResult;
import com.ikonke.iot.alarm.service.MailService;
import org.apache.commons.lang3.StringUtils;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.influxdb.querybuilder.BuiltQuery.QueryBuilder.*;
import static org.influxdb.querybuilder.time.DurationLiteral.MILLISECONDS;

/**
 * @Author: liull
 * @Description:
 * @Date: Created in 19:55 2020/6/15
 * @Modified By:
 */
@RestController
public class TestController {

    @Autowired
    private MailService mailService;

    @GetMapping("/testMail")
    public R mail1(MailDO mailDO) {
        try {
            mailService.sendTextMail(mailDO);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    @GetMapping("/htmlMail")
    public R mail2(MailDO mailDO) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("附件名", "附件的绝对路径");
            mailDO.setAttachment(map);
            mailService.sendHtmlMail(mailDO, false);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    @GetMapping("/templateMail")
    public R mail3(MailDO mailDO) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("username", "我变大了");
            mailDO.setAttachment(map);
            mailService.sendTemplateMail(mailDO);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
        return R.ok();
    }

//    @GetMapping("/hello")
//    public Mono<String> hello() {
//        return Mono.just("love liyanlin");
//    }

//    public List<CcuStateResp> queryOnlineHistory(QueryOnlineHistoryReq req) {
//        List<CcuStateResp> resp = new ArrayList<>();
//        final AsyncResult<QueryResult> res = new AsyncResult<>();
//        // 转换为毫秒ms
//        String startTime = req.getStartTime();
//        String endTime = req.getEndTime();
//        long start = DateUtil.parse(startTime, DatePattern.NORM_DATETIME_PATTERN).getTime();
//        long end = DateUtil.parse(endTime, DatePattern.NORM_DATETIME_PATTERN).getTime();
//        Query select = select()
//                //                .column("value")
//                .column("fonline")
//                .from(influxProperties.getDatabase(), influxProperties.getMeasurement())
//                .where(eq("clientId", req.getCcu_id()))
//                .and(gte("time", ti(start, MILLISECONDS)))
//                .and(lte("time", ti(end, MILLISECONDS)))
//                .orderBy(desc())
//                .limit(100);
//        this.influxDB.query(select, res.resultConsumer, res.errorConsumer);
//        try {
//            QueryResult result = res.result();
//            QueryResult.Result results = result.getResults().get(0);
//            if (CollectionUtils.isEmpty(results.getSeries())) {
//                return Lists.newArrayList();
//            }
//            QueryResult.Series series = results.getSeries().get(0);
//            List<List<Object>> values = series.getValues();
//            values.forEach(value -> {
//                CcuStateResp ccuStateResp = new CcuStateResp();
//                value.forEach(item -> {
//                    String s = String.valueOf(item);
//                    if (StringUtils.containsAny(s, "ONLINE", "OFFLINE")) {
//                        // 处理 fonline column
//                        ccuStateResp.setState(s.contains("ONLINE") ? 1 : 0);
//                    } else {
//                        // 处理 time column utc转东八区时间
//                        DateTimeFormatter formatter0 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("Asia/Shanghai"));
//                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssz");
//                        ZonedDateTime zoneTime = ZonedDateTime.parse(s, formatter);
//                        String ts = zoneTime.withFixedOffsetZone().format(formatter0);
//                        ccuStateResp.setTs(ts);
//                    }
//                });
//                resp.add(ccuStateResp);
//            });
//
//            log.info("series.getValues()====>>>>{}", JSON.toJSONString(values));
//            return resp;
//        } catch (Throwable throwable) {
//            throwable.printStackTrace();
//            log.error("异步查询主机[{}]在线历史失败", req.getCcu_id());
//        }
//        return Lists.newArrayList();
//    }
}
